<?php

namespace App\Modules\Admin\Controllers;


use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function index()
    {
        $users = User::query()->orderBy('created_at','desc')->paginate(20);
        return view('admin::user.index',['users' => $users]);
    }

    public function getOne(Request $request)
    {
        $user = User::find($request->id);
        $response = [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'roles' => mb_split(',',$user->roles),
            'disabled_duration' => $user->disabled_duration
        ];
        return response()->json($response);
    }

    public function save(Request $request)
    {
        $rule = ['id' => 'required'];
        $data = [];
        if ($request->input('password')) {
            $rule['password'] = 'confirmed:password_confirmation';
            $data['password'] = Hash::make($request->input('password'));
        }
        $data['name'] = $request->input('name');
        Validator::make($request->all(),$rule)->validate();
        $data['roles'] = implode(',',$request->input('roles'));

        if ($request->input('is_disabled')) {
            $data['disabled_duration'] = $request->input('disabled_duration');
            $data['disabled_at'] = date('Y-m-d H:i:s');
        }

        User::where('id',$request->input('id'))->update($data);
    }
}
